

let cfg = require('./utils/cfg');

class Texture2D{
    constructor(img) {
        let gl = cfg.gl;
        let texId = this._texId = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D,texId);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA,gl.UNSIGNED_BYTE, img);
        gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
        gl.bindTexture(gl.TEXTURE_2D,null);

        this._width = img.width;
        this._height = img.height;
        this._img = img;
    }

    get img(){
        let src = this._img.src;
        return window.path.basename(src);
    }

    get width(){
        return this._width;
    }
    get height(){
        return this._height;
    }

    texId(){
        return this._texId;
    }

    useTexture(){
        if(!this._texId){
            throw new Error('texId is null!');
        }
        let gl = cfg.gl;
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D,this._texId);
    }

    dispose(){
        if(this._texId){
            console.log('del texture2d');
            let gl = cfg.gl;
            gl.deleteTexture(this._texId);
            this._texId = null;
        }
    }
}

module.exports = Texture2D;
